//
//  FTT_PickerView.m
//  FTT_PickerView
//
//  Created by cmcc on 16/8/31.
//  Copyright © 2016年 cmcc. All rights reserved.
//

#import "FTT_PickerView.h"

#define KscreenWidth  [UIScreen mainScreen].bounds.size.width
#define KscreenHeight [UIScreen mainScreen].bounds.size.height

#define BtnW 60
#define toolH 40
#define BGH  260

@interface FTT_PickerView ()<UIPickerViewDelegate,UIPickerViewDataSource> {
    // beijing
    UIView        *_BGView ;
    // 取出所有数据(json类型,在pilist里面)
    NSArray       *_Allarray;
    // 省的数组
    NSMutableArray *_ProvinceAry;
    // 市的数组
    NSMutableArray *_CityAry;
    // 县的数组
    NSMutableArray *_DistrictAry;
    // 主要的选择器
    UIPickerView   *_PickerView;
    // 用于记录选中哪个省的索引
    NSInteger _ProIndex;
    // 用于记录选中哪个市的索引
    NSInteger _CityIndex;
    // 用于记录选中哪个县的索引
    NSInteger _DistrictIndex;
}
@end

@implementation FTT_PickerView


static FTT_PickerView *shareInstance = nil;


- (instancetype)initWithFrame:(CGRect)frame PickerViewType:(FTT_PickerViewShowType)showtype DataSoucre:(NSMutableDictionary *)array {
    self = [super init];
    if (self) {
        self.userInteractionEnabled = YES;
        self.frame = frame;
        self.num = 3;
        [self loadata:array];
        [self createUI:showtype];
    }
    return self;
}
// 获取数据
- (void)loadata:(NSMutableDictionary *)plist {
    _ProvinceAry = [NSMutableArray new];
    _CityAry = [NSMutableArray new];
    _DistrictAry = [NSMutableArray new];
    if (plist) {
        _ProvinceAry = [plist objectForKey:[[plist allKeys] objectAtIndex:0]];
        
        if ([[plist allKeys] count] == 2) {
             _CityAry = [plist objectForKey:[[plist allKeys] objectAtIndex:1]];
        }

       
        if ([[plist allKeys] count] == 3) {
             _DistrictAry = [plist objectForKey:[[plist allKeys] objectAtIndex:2]];
        }

       
     
    }else{
        _Allarray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"]];
        for (NSDictionary *dic  in _Allarray) {
            [_ProvinceAry addObject:[[dic allKeys] firstObject]];
        }
        if (!_ProvinceAry.count) {
          //  NSLog(@"没有数据啊大哥");
        }
        for (NSDictionary *dic in _Allarray) {
            if ([dic objectForKey:_ProvinceAry[_ProIndex]]) {
                _CityAry = [NSMutableArray arrayWithArray:[[dic objectForKey:_ProvinceAry[_ProIndex]] allKeys]];
                [_PickerView reloadComponent:1];
                [_PickerView selectRow:0 inComponent:1 animated:YES];
                _DistrictAry = [NSMutableArray arrayWithArray:[[dic objectForKey:_ProvinceAry[_ProIndex]] objectForKey:_CityAry[0]]];
                [_PickerView reloadComponent:2];
                [_PickerView selectRow:0 inComponent:2 animated:YES];
            }
        }
    }
}
// 创建UI
- (void)createUI:(FTT_PickerViewShowType )type {
    self.showType = type;
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    }];
    _BGView = [[UIView alloc]init];
    _BGView.layer.masksToBounds = YES;
    _BGView.layer.cornerRadius = 10 ;
    if (FTT_PickerViewShowTypeSheet == type) {
        _BGView.frame = CGRectMake(0, 0, KscreenWidth, BGH);
        _BGView.center = self.center;
        
    }else {
        _BGView.frame = CGRectMake(0, KscreenHeight, KscreenWidth, BGH);
        
    }
    [self addSubview:_BGView];
    UIView *tool = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, toolH)];
    tool.backgroundColor = [UIColor whiteColor];
    [_BGView addSubview:tool];
    NSArray *titileArray = @[@"取消",@"确定"];
    for (int i = 0; i < 2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0 + (KscreenWidth - BtnW) * i, 0, BtnW, toolH);
        [btn setTitle:titileArray[i] forState:UIControlStateNormal];
        btn.tag = 100 + i;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
        [_BGView addSubview:btn];
    }
    
    _PickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, toolH, KscreenWidth, _BGView.frame.size.height - toolH)];
    _PickerView.delegate = self;
    _PickerView.dataSource = self;
    _PickerView.backgroundColor = [UIColor colorWithRed:237 green:237 blue:237 alpha:1];
    [_BGView addSubview:_PickerView];

}


#pragma mark ---- UIPickerVIewDelegate 
// 自定义每个pickerview 的lable
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLable = [UILabel new];
    pickerLable.numberOfLines = 0;
    pickerLable.textAlignment = NSTextAlignmentCenter;
    [pickerLable setFont:[UIFont boldSystemFontOfSize:17]];
    pickerLable.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLable;
}
// 点击了那一个
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        _ProIndex = row;
        _CityIndex = 0 ;
        _DistrictIndex = 0;
        for (NSDictionary *dic  in _Allarray) {
            if ([dic objectForKey:_ProvinceAry[_ProIndex]]) {
                _CityAry = [NSMutableArray arrayWithArray:[[dic objectForKey:_ProvinceAry[_ProIndex]] allKeys]];
                [_PickerView reloadComponent:1];
                [_PickerView selectRow:0 inComponent:1 animated:YES];
                _DistrictAry = [NSMutableArray arrayWithArray:[[dic objectForKey:_ProvinceAry[_ProIndex]] objectForKey:_CityAry[0]]];
                [_PickerView reloadComponent:2];
                [_PickerView selectRow:0 inComponent:2 animated:YES];
            }
        }
    }
    if (component == 1) {
        _CityIndex = row;
        _DistrictIndex = 0;
        for (NSDictionary *dci in _Allarray) {
            if ([dci objectForKey:_ProvinceAry[_ProIndex]]) {
                _DistrictAry = [[dci objectForKey:_ProvinceAry[_ProIndex]] objectForKey:_CityAry[_CityIndex]];
                [_PickerView reloadComponent:2];
                [_PickerView selectRow:0 inComponent:2 animated:YES];
            }
        }
    }
    if (component == 2) {
        _DistrictIndex = row;
    }
}
// 设置每个cell的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return  KscreenWidth / 3.0;
}



// 每个cell显示的内容
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return [_ProvinceAry objectAtIndex:row];
    }else if (component == 1){
        return [_CityAry objectAtIndex:row];
    }else if (component == 2){
        return [_DistrictAry objectAtIndex:row];
    }
    
    return nil;
}
// 对应的每个cell的个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component==0) {
        return _ProvinceAry.count;
    }else if (component == 1){
        return _CityAry.count;
    }else if (component == 2){
        return _DistrictAry.count;
    }
    return 0;
}
// 有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return _num;
}
// 按钮触发的事件
- (void)btn:(UIButton *)btn {
    __weak typeof (UIView *)blockview = _BGView;
    __weak typeof(self) weakself= self;
    __block int blockH= KscreenHeight;
    switch (btn.tag) {
        case 101:
        {
            if (self.select) {
                if (_CityAry.count ==0) {
                    _CityAry[_CityIndex] = @"";
                }
                if (_DistrictAry.count ==0) {
                    _DistrictAry[_DistrictIndex] = @"";
                }
                self.select(_ProvinceAry[_ProIndex],_CityAry[_CityIndex],_DistrictAry[_DistrictIndex]);
            }
            [UIView animateWithDuration:0.3 animations:^{
                CGRect bjf = blockview.frame;
                bjf.origin.y = blockH;
                blockview.frame = bjf;
                weakself.alpha = 0.1;
            } completion:^(BOOL finished) {
                [weakself removeFromSuperview];
            }];
        }
            break;
        case 100:
        {
            [UIView animateWithDuration:0.3 animations:^{
                CGRect bjf = blockview.frame;
                bjf.origin.y = blockH;
                blockview.frame = bjf;
                weakself.alpha = 0.1;
            } completion:^(BOOL finished) {
                [weakself removeFromSuperview];
            }];
        }
            break;
    }
}
//
-(void)showCityView:(void (^)(NSString *, NSString *, NSString *))selectStr{
    
    self.select = selectStr;
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    __weak typeof(UIView*)blockview = _BGView;
    __block int blockH = KscreenHeight;
    __block int bgh = BGH;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect bjf = blockview.frame;
        if (self.showType == FTT_PickerViewShowTypeSheet) {
            blockview.center = self.center;
        }else {
            bjf.origin.y = blockH- bgh;
            blockview.frame = bjf;
        }
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint point = [[touches anyObject] locationInView:self];
    if (!CGRectContainsPoint(_BGView.frame, point)) {
        UIButton *btn = (UIButton *)[_BGView viewWithTag:100];
        [self btn:btn];
    }
}

@end
